package com.token.test.submit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.token.sysflow.action.GetPathApproverAction;
import com.token.sysflow.action.SubmitFlowAction;
import com.token.test.util.FuncUtilTest;
import com.token.test.util.IntegrateSqlTest;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

/**
 * 测试退回再提交
 * @author chenjianxiong 2020/4/27
 */
public class SubmitFlow3 {
    private static FuncUtilTest f;
    private static IntegrateSqlTest iSql;

    public static void main(String[] args) {

        try {
            SubmitFlowAction submitFlowAction = new SubmitFlowAction();
            String path = submitFlowAction.getClass().getClassLoader().getResource("json/SubmitFlowAction.json").getPath();
            String json = FileUtils.readFileToString(new File(path), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(json);

            JSONObject tmp,returnJson,selectJson;
            JSONArray data;
            String keyUuid, approves,curUser;
            iSql = new IntegrateSqlTest();
            iSql.initCon();

            approves = "4987ccf58ba640df9dd6d8d1d91d9062|100003";
            String mainKeyUuid = "4987ccf58ba640df9dd6d8d1d91d9062";

            for (int t = 0; t < 10; t++) {
                System.out.println("============================开始提交==========================：" + (t + 1));
//                if (approves.equals("")) {
//                    throw new Exception("办理人为空！");
//                }

                String[] curUsers = approves.split(",");
                String[] arr1 = curUsers[0].split("\\|");
                curUser = arr1[1];
                keyUuid = arr1[0];


                tmp = jsonObject.getJSONObject("getPath_02");
                tmp.put("keyUnid", keyUuid);
                tmp.put("curUser", curUser);

                f = new FuncUtilTest(tmp);
                System.out.println("====提交框====");
                new GetPathApproverAction().executeAction(f, iSql);
                returnJson = f.getJsonData();

                if (!testOk(returnJson)) {
                    return;
                }
                printSelectDiv(returnJson.getJSONArray("data"));

                System.out.println(" ");
                //==================================================
                data = returnJson.getJSONArray("data");
                if (data != null) { //审批
                    selectJson = data.getJSONObject(1);
                    System.out.println("curUser = " + arr1[1]);
                    tmp = jsonObject.getJSONObject("task_02");
                    tmp.put("stepId", selectJson.getString("stepId"));
                    tmp.put("keyUnid", mainKeyUuid);
                    tmp.put("selectApprovers", getApprover(selectJson));
                    tmp.put("curUser", arr1[1]);
                    tmp.put("subKeyUnid", keyUuid);

                    System.out.println("====提交流程====");
                    f = new FuncUtilTest(tmp);

                    new SubmitFlowAction().executeAction(f, iSql);
                    returnJson = f.getJsonData();
                    if (!testOk(returnJson)) {
                        return;
                    }
                    approves = printNextApproves(returnJson);
                    if(true){
                        return;
                    }
                } else { // 会签会审类，

                    if (curUsers.length >= 2) {
                        System.out.println("====双线程并行提交流程====");

                        String[] arr2 = curUsers[0].split("\\|");
                        String[] arr3 = curUsers[1].split("\\|");
//                        curUser = arr2[1];
                        keyUuid = arr1[0];

                        System.out.println(">>>>>>>开始线程1 = " + curUsers[0]);
                        Future<JSONObject> future1 = getAsync(jsonObject, keyUuid, arr2[1]);

                        System.out.println(">>>>>>>开始线程2 = " + curUsers[1]);
                        Future<JSONObject> future2 = getAsync(jsonObject, keyUuid, arr3[1]);

                        JSONObject temp1 = future1.get();
                        JSONObject temp2 = future2.get();

                        if (!testOk(temp1)) {
                            return;
                        }

                        if (!testOk(temp2)) {
                            return;
                        }


                        System.out.println(">>>>>>>线程1执行完成");
                        System.out.println(">>>>>>>线程2执行完成");

                        JSONArray flowData1 = temp1.getJSONArray("flowData");
                        JSONArray flowData2 = temp2.getJSONArray("flowData");
//                        System.out.println("flowData1.size() = " + flowData1.size());
//                        System.out.println("flowData2.size() = " + flowData2.size());
                        if (flowData1.size() == flowData2.size()) {
                            JSONObject jsonTmp1 = flowData1.getJSONObject(0);
                            JSONArray nextApproves1 = jsonTmp1.getJSONArray("nextApproves");

                            JSONObject jsonTmp2 = flowData2.getJSONObject(0);
                            JSONArray nextApproves2 = jsonTmp2.getJSONArray("nextApproves");
                            if(nextApproves1.size()> nextApproves2.size()){
                                returnJson = temp2;
                                approves = printNextApproves(temp2);
                            }else {
                                returnJson = temp1;
                                approves = printNextApproves(temp1);
                            }
                        }else if (flowData1.size() > flowData2.size()) {
//                            System.out.println("temp2 = " + temp2);
                            returnJson = temp2;
                            approves = printNextApproves(temp2);
                        } else {
//                            System.out.println("temp1 = " + temp1);
                            returnJson = temp1;
                            approves = printNextApproves(temp1);
                        }


                    } else {
                        System.out.println("====提交流程====");
                        String[] arr2 = curUsers[0].split("\\|");
                        tmp = jsonObject.getJSONObject("task_02");
                        tmp.put("keyUnid", arr2[0]);
                        tmp.put("curUser", arr2[1]);
                        f = new FuncUtilTest(tmp);

                        new SubmitFlowAction().executeAction(f, iSql);
                        returnJson = f.getJsonData();
                        if (!testOk(returnJson)) {
                            return;
                        }
                        approves = printNextApproves(returnJson);
                    }
                }

                System.out.println("============================结束提交==========================：" + (t + 1));
//                stepName = returnJson.getString("flowName") + "-" + returnJson.getString("stepName");
                if (returnJson.getIntValue("isReturned") == 1) { //结束环节
                    System.out.println("退回流程");
                    break;
                }

                if (returnJson.getIntValue("flowStatus") == 2 && returnJson.getIntValue("flowType") == 1) { //结束环节
                    System.out.println("审批结束");
                    break;
                }


                System.out.println(" ");
            }
            //==================================================
            System.out.println("===========测试完成=========");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @param jsonObject
     * @param keyUnid
     * @param curUser
     * @return
     */
    public static Future<JSONObject> getAsync(JSONObject jsonObject, String keyUnid, String curUser) {
        CompletableFuture<JSONObject> futurePrice = new CompletableFuture<>();
        new Thread(() -> {
            try {
                //在另一个线程中执行计算
                JSONObject tmp = new JSONObject();
                tmp.putAll(jsonObject.getJSONObject("task_02"));
                tmp.put("keyUnid", keyUnid);
                tmp.put("curUser", curUser);
                FuncUtilTest f1 = new FuncUtilTest(tmp);

                new SubmitFlowAction().executeAction(f1, iSql);
                JSONObject returnJson = f1.getJsonData();
                futurePrice.complete(returnJson);
            } catch (Exception ex) {
                //抛出异常
                futurePrice.completeExceptionally(ex);
            }
        }).start();
        return futurePrice;
    }

    /**
     * @param returnJson
     * @return
     */
    private static String printNextApproves(JSONObject returnJson) {
        JSONArray flowData = returnJson.getJSONArray("flowData");
        JSONArray approver;
        JSONObject jsonObject;
        StringBuffer blr = new StringBuffer(200);
        StringBuilder name = new StringBuilder(50);
        boolean iss = false;
        for (int ii = 0; ii < flowData.size(); ii++) {
            jsonObject = flowData.getJSONObject(ii);
            approver = jsonObject.getJSONArray("nextApproves");
            blr.append(" ").append(returnJson.getString("approvalText")).append(" 办理人：");

            for (int j = 0; j < approver.size(); j++) {
                if (iss) {
                    blr.append(" || ");
                    name.append(",");
                }
                JSONObject appr = approver.getJSONObject(j);
                blr.append(appr.getString("name")).append("-").append(appr.getString("id"));
                if (!appr.getString("auth").equals("")) {
                    blr.append("被[").append(appr.getString("auth")).append("]授权");
                }
                name.append(jsonObject.getString("keyUnid")).append("|").append(appr.getString("id"));
                iss = true;
            }
        }
        System.out.println(blr);
        return name.toString(); //办理人
    }

    /**
     * @param data
     */
    private static void printSelectDiv(JSONArray data) {
        StringBuffer blr;
        if (data == null) {
            return;
        }

        for (int i = 0; i < data.size(); i++) {
            blr = new StringBuffer(50);
            JSONObject liuxiang = data.getJSONObject(i);
            JSONArray approver = liuxiang.getJSONArray("approver");
            blr.append("--->流向").append(i + 1).append(":").append(liuxiang.getString("stepName")).append("(");
            for (int j = 0; j < approver.size(); j++) {
                if (j > 0) {
                    blr.append(" | ");
                }
                JSONObject appr = approver.getJSONObject(j);
                blr.append(appr.getString("name")).append("-").append(appr.getString("id"));

            }
            System.out.println(blr.append(")"));
        }

    }

    /**
     * @param selectJson
     * @return
     */
    private static String getApprover(JSONObject selectJson) {
        JSONArray approver = selectJson.getJSONArray("approver");
        StringBuilder buf = new StringBuilder(50);
        boolean bb = false;
        for (int i = 0; i < approver.size(); i++) {
            JSONObject o = approver.getJSONObject(i);
            if (o.getBooleanValue("checked")) {
                if (bb) {
                    buf.append(";");
                }
                buf.append(o.getString("id"));
            }
            bb = true;
        }
        return buf.toString();
    }

    /**
     * @param returnJson
     * @return
     */
    private static boolean testOk(JSONObject returnJson) {
        if (returnJson.getIntValue("code") != 0) {
            System.out.println("===遇到错误终止测试===");
            return false;
        } else {
            return true;
        }

    }

}
